<?php

namespace api\modules\v1\forms\dingtalk;

use Yii;
use yii\base\Model;
use common\models\member\Member;

/**
 *
 * Class LoginForm
 * @package api\modules\v1\forms\dingtalk
 */
class LoginForm extends Model
{
    /**
     * 钉钉unionid
     *
     * @var
     */
    public $ding_unionid;

    /**
     * 用户信息
     *
     * @var
     */
    protected $member;


    public function rules()
    {
        return [
            // 参数验证
            [['ding_unionid'], 'required', 'message' => '{attribute}不能为空', 'on' => ['fast_login']],

            [['ding_unionid'], 'checkDingUnionid', 'skipOnEmpty' => false, 'on' => ['fast_login']],
        ];
    }

    public function scenarios()
    {
        $scenarios = parent::scenarios();

        // 快速登录
        $scenarios['fast_login'] = ['ding_unionid'];

        return $scenarios;
    }

    /**
     * @return array
     */
    public function attributeLabels()
    {
        return [
            'ding_unionid' => 'ding_unionid',
        ];
    }

    /**
     * 检验用户UID
     *
     * @param $attribute
     * @return bool
     */
    public function checkDingUnionid($attribute)
    {
        if ($this->hasErrors()) {
            return true;
        }

        $member = $this->getMember();
        if (empty($member)) {
            $this->addError($attribute, '未绑定账户');
            return true;
        }

        if ($member->status != Member::STATUS_ENABLE) {
            $this->addError($attribute, '账户异常');
            return true;
        }

        // 超管不验证
        if ($member->is_super == Member::IS_SUPER_YES) {
            return true;
        }

        // 用户属性列表
        $memberAttrList = Yii::$app->services->attr->findList([
            'member_id' => $member->id,
        ]);

        $isError = true;
        foreach ($memberAttrList as $row) {
            if ($row['project_id'] && $row['department_id']) {
                $isError = false;
                break;
            }
        }
        $isError && $this->addError($attribute, '账户未绑定项目或部门');
    }

    /**
     * 获取用户信息
     *
     * @return Member|null
     */
    public function getMember()
    {
        if (empty($this->member)) {
            $this->member = Yii::$app->services->member->findInfo([
                'ding_unionid' => $this->ding_unionid
            ]);
        }

        return $this->member;
    }
}
